<?php

class OfferController extends My_Controller_Action {

    const SESSION_KEY = 'offer-add';

    public function imageAction() {
        Zend_Layout::getMvcInstance()->disableLayout();
        $id = $this->_getParam('id', 0);
        $width = $this->_getParam('width', 100);
        $height = $this->_getParam('height', 100);
        $overScale = intval($this->_getParam('overScale', 0));
        $overScale = $overScale == 0 ? 0 : 1;
        $file = implode('_', array($id, $width, $height, $overScale)) . '.jpg';
        $token = $this->_getParam('token');
        if (empty($token)) {
            die('ERROR1');
        }
        $bean = $this->getWizardBean($token);
        if (empty($bean->photoUploadPath)) {
            die('ERROR2');
        }
        $uploadDir = $bean->photoUploadPath;
        $cachePath = $uploadDir . '/cache';
        if (!file_exists($cachePath)) {
            mkdir($cachePath, 0777, true);
        }
        $cachePath .= '/' . $file;
        if (file_exists($cachePath)) {
            $content = file_get_contents($cachePath);
            header('Content-Type: image/jpg');
            die($content);
        }
        $path = realpath($uploadDir) . '/' . $id . '.jpg';
        if (!file_exists($path)) {
            $path = realpath($uploadDir) . '/../../0.jpg';
        }
        $imgUtils = new My_ImageUtils();
        $imgUtils->load($path);
        $imgUtils->resizeToBounds($width, $height, $overScale);
        $imgUtils->save($cachePath);
        $content = file_get_contents($cachePath);
        header('Content-Type: image/jpg');
        die($content);
    }

    public function uploadPhotoAction() {
        $this->view->token = $token = $this->_getParam('token');
        $currStep = $this->getCurrentStep($token);
        $bean = $this->getWizardBean($token);
        if ($currStep != Application_Model_DAO_Offer::STEP_PHOTO) {
            $this->addError($this->translate('XXX_OFFER_UPLOAD_PHOTO_WRONG_STEP'));
            $url = $this->url(array('controller' => 'offer', 'action' => 'add'), 'default', true);
            $this->_redirect($url);
        }

        // @todo check allowed photos - restrictions
        $daoOffer = new Application_Model_DAO_Offer();
        $photoValid = $daoOffer->validatePhotos($bean);
        if ($photoValid !== true) {
            $this->ajaxPacket = array('photoAmoutExceeded' => '1');
            $errors = array();
            if (is_array($photoValid)) {
                foreach ($photoValid as $err) {
                    $errors[] = $err;
                }
            } else {
                $errors[] = $photoValid;
            }
            if (empty($errors)) {
                $errors[] = $this->translate('XXX_OFFER_UPLOAD_PHOTO_INVALID_PHOTOS');
            }
            foreach ($errors as $err) {
                $this->addError($err);
            }
            $url = $this->url(array('controller' => 'offer', 'action' => 'add', 'token' => $token), 'default', true);
            $this->_redirect($url);
        }


        if (!isset($bean->photoUploadPath) || empty($bean->photoUploadPath)) {
            $date = date('YmdHis');
            $uploadDir = APPLICATION_PATH . '/../uploaded/image/tmp/' . $date . '-' . $token;
            $bean->photoUploadPath = $uploadDir;
        } else {
            $uploadDir = $bean->photoUploadPath;
        }
        @mkdir($uploadDir, 0777, true);


        if (!empty($_FILES)) {
            $tempFile = $_FILES['file_upload']['tmp_name'];
            $targetPath = rtrim($uploadDir, '/');
            // Validate the file type
            $fileTypes = array('jpg', 'jpeg', 'png'); // File extensions
            $fileParts = pathinfo($_FILES['file_upload']['name']);
            $fileName = uniqid();
            $ext = strtolower($fileParts['extension']);
            $targetFile = rtrim($targetPath, '/') . '/' . $fileName . '.' . $ext;
            if (in_array($ext, $fileTypes)) {
                move_uploaded_file($tempFile, $targetFile);
                if ($ext != 'jpg') {
                    $imgUtils = new My_ImageUtils();
                    $imgUtils->load($targetFile);
                    $targetJpgFile = rtrim($targetPath, '/') . '/' . $fileName . '.jpg';
                    $imgUtils->save($targetJpgFile);
                    @unlink($targetFile);
                    $targetFile = $targetJpgFile;
                }
                $result = array(
                    'name' => $_FILES['file_upload']['name'],
                    'id' => $fileName,
                );
                $isMain = false;
                if (empty($bean->photos)) {
                    $isMain = true;
                    $bean->photoMainId = $fileName;
                }
                $bean->photos[$fileName] = array(
                    'name' => $result['name'],
                    'id' => $fileName,
                    'path' => $targetFile,
                    'main' => $isMain,
                );

                $photoValid = $daoOffer->validatePhotos($bean);
                if ($photoValid !== true) {
                    $result['photoAmoutExceeded'] = 1;
                }
                $result['html'] = $this->view->partial('offer/add-step-photo-thumb.phtml', array('bean' => $bean, 'p' => $bean->photos[$fileName], 'token' => $token));
                $this->ajaxPacket = $result;
                $this->addSuccess($this->translate('XXX_OFFER_PHOTO_UPLOAD_SUCCESS'));
                $url = $this->url(array('controller' => 'offer', 'action' => 'add', 'token' => $token), 'default', true);
                $this->_redirect($url);
            } else {
                $this->addError($this->translate('XXX_OFFER_PHOTO_UPLOAD_INCORRECT_TYPE'));
                $url = $this->url(array('controller' => 'offer', 'action' => 'add', 'token' => $token), 'default', true);
                $this->_redirect($url);
            }
        } else {
            $this->addError($this->translate('XXX_OFFER_UPLOAD_PHOTO_NOT_PHOTO_TO_UPLOAD'));
            $url = $this->url(array('controller' => 'offer', 'action' => 'add', 'token' => $token), 'default', true);
            $this->_redirect($url);
        }
    }

    public function deletePhotoAction() {
        $token = $this->_getParam('token');
        $currStep = $this->getCurrentStep($token);
        $bean = $this->getWizardBean($token);
        if ($currStep != Application_Model_DAO_Offer::STEP_PHOTO) {
            $this->addError($this->translate('XXX_OFFER_DELETE_PHOTO_WRONG_STEP'));
            $url = $this->url(array('controller' => 'offer', 'action' => 'add', 'token' => $token), 'default', true);
            $this->_redirect($url);
        }
        $pid = $this->_getParam('id');
        if (empty($pid)) {
            $this->addError($this->translate('XXX_OFFER_DELETE_PHOTO_NOT_EXIST'));
            $url = $this->url(array('controller' => 'offer', 'action' => 'add', 'token' => $token), 'default', true);
            $this->_redirect($url);
        }
        if (!isset($bean->photos[$pid])) {
            $this->addError($this->translate('XXX_OFFER_DELETE_PHOTO_NOT_EXIST'));
            $url = $this->url(array('controller' => 'offer', 'action' => 'add', 'token' => $token), 'default', true);
            $this->_redirect($url);
        }
        $photo = $bean->photos[$pid];
        @unlink($photo['path']);
        unset($bean->photos[$pid]);
        if ($pid == $bean->photoMainId) {
            $bean->photoMainId = null;
            foreach ($bean->photos as $p) {
                $bean->photoMainId = $p['id'];
                break;
            }
        }
        $ajaxData = array('id' => $pid);
        $daoOffer = new Application_Model_DAO_Offer();
        $photoValid = $daoOffer->validatePhotos($bean);
        if ($photoValid === true) {
            $ajaxData['photoAmoutExceeded'] = 0;
        } else {
            $ajaxData['photoAmoutExceeded'] = 1;
        }
        $this->ajaxPacket = $ajaxData;
        $this->addSuccess($this->translate('XXX_OFFER_DELETE_PHOTO_SUCCESS'));
        $url = $this->url(array('controller' => 'offer', 'action' => 'add', 'token' => $token), 'default', true);
        $this->_redirect($url);
    }

    public function addAction() {
        $this->userLoginRequired();
        $this->setContentTitle(_('XXX_OFFER_ADD_PAGE_TITLE'));

        $this->view->token = $token = $this->_getParam('token');

        $urlParams = array(
            'module' => 'default',
            'controller' => 'offer',
            'action' => 'add',
        );

        $currStep = $this->getCurrentStep($token);
        if (empty($currStep)) {
            $this->_redirect($this->url($urlParams));
            return;
        }
        if ($currStep == Application_Model_DAO_Offer::STEP_LOGIN) {
            $token = $this->initWizard();
            $urlParams['token'] = $token;
            if ($this->_hasParam('id')) {
                $urlParams['id'] = $this->_getParam('id');
            }
            $url = $this->url($urlParams);
            $this->_redirect($url);
        }
        $bean = $this->getWizardBean($token);
        $this->view->bean = $bean;
        $urlParams['token'] = $token;
        if ($currStep == Application_Model_DAO_Offer::STEP_CATEGORY) {
            if ($this->_hasParam('id')) {
                $categoryCode = $this->_getParam('id');
                if (!$categoryCode) {
                    $this->addError(_('XXX_OFFER_ADD_CATEGORY_NOT_EXISTS_ERROR'));
                    $this->_redirect($this->url($urlParams));
                    return;
                }
                $daoCategory = new Application_Model_DAO_Category();
                $category = $daoCategory->getByCode($categoryCode);
                if (!$category) {
                    $this->addError(_('XXX_OFFER_ADD_CATEGORY_NOT_EXISTS_ERROR'));
                    $this->_redirect($this->url($urlParams));
                    return;
                }
                $bean->currentStep = Application_Model_DAO_Offer::STEP_TYPE;
                $bean->categoryId = $category['category_id'];
                $bean->categoryName = $category['name'];
                $bean->offerTemplateId = $category['offer_template_id'];
                $url = $this->url($urlParams);
                $this->_redirect($url);
            } else {
                $daoCategory = new Application_Model_DAO_Category();
                $cats = $daoCategory->getFullCategories();
                $this->view->categories = $cats;
                $this->renderScript('offer/add-step-category.phtml');
                return;
            }
        }
        if ($currStep == Application_Model_DAO_Offer::STEP_TYPE) {
            if ($this->_hasParam('type')) {
                $type = $this->_getParam('type');
                if (in_array($type, array('free', 'paid'))) {
                    $bean->type = $type;
                    $bean->currentStep = Application_Model_DAO_Offer::STEP_FORM;
                    $this->_redirect($this->url($urlParams));
                }
            } else {
                $this->renderScript('offer/add-step-type.phtml');
                return;
            }
        }
        if ($currStep == Application_Model_DAO_Offer::STEP_FORM) {
            $form = new Application_Form_Offer_Generic($bean->categoryId, $bean);

            if (!$this->_request->isPost() || !$form->isValid($_POST)) {
                // @todo tutaj formularz uzupełnić danymi
                if (!$this->_request->isPost()) {
                    if (isset($bean->offer)) {
                        $form->populate($bean->offer);
                    }
                }
                $this->view->form = $form;
                $this->renderScript('offer/add-step-form.phtml');
                return;
            } else {
                $data = $form->getValues();
                $bean->offer = $data;
                $bean->currentStep = Application_Model_DAO_Offer::STEP_PHOTO;
                $this->_redirect($this->url($urlParams));
            }
        }
        if ($currStep == Application_Model_DAO_Offer::STEP_PHOTO) {
            if ($this->_getParam('step') == 'next') {
                $bean->currentStep = Application_Model_DAO_Offer::STEP_PREVIEW;
                $this->_redirect($this->url($urlParams));
            } else {
                if (!isset($bean->photos)) {
                    $bean->photos = array();
                }
                $this->renderScript('offer/add-step-photo.phtml');
            }
        }
        if ($currStep == Application_Model_DAO_Offer::STEP_PREVIEW) {
            if ($this->_request->isPost() && $_POST['agreement'] == 1 && $this->_getParam('step') == 'next') {
                $type = $bean->type;
                if ($type == Application_Model_DAO_Offer::TYPE_FREE) {
                    $currStep = Application_Model_DAO_Offer::STEP_PUBLISH;
                    $bean->currentStep = $currStep;
                } else {
                    $currStep = Application_Model_DAO_Offer::STEP_PAYMENT;
                    $bean->currentStep = $currStep;
//                    $bean->currentStep = Application_Model_DAO_Offer::STEP_PAYMENT;
//                    $this->_redirect($this->url($urlParams));
                }
            } else {
                if ($this->_request->isPost()) {
                    $this->view->agreementRequired = true;
                }
                $offer = $bean->offer;
                $offer['attributes'] = array();
                if (empty($bean->photos)) {
                    $offer['images'] = array();
                    $offer['image_code'] = null;
                    $offer['image_id'] = 0;
                } else {
                    $images = array();

                    foreach ($bean->photos as $img) {
                        $images[] = array(
                            'code' => $img['id'],
                            'title' => '',
                            'name' => '',
                        );
                    }
                    $offer['images'] = $images;
                    $offer['image_code'] = $bean->photos[$bean->photoMainId]['id'];
                }

                $daoOfferTemplate = new Application_Model_DAO_OfferTemplate();
                $template = $daoOfferTemplate->getTemplate($bean->offerTemplateId);
                if (empty($template) || empty($template['attributes'])) {
                    $attrsTmp = array();
                } else {
                    $attrsTmp = $template['attributes'];
                }
                $attrs = array();
                foreach ($attrsTmp as $attr) {
                    $attrs['otaid_' . $attr['offer_template_attribute_id']] = $attr;
                }

                foreach ($offer as $key => $val) {
                    if (isset($attrs[$key])) {
                        $attrs[$key]['value'] = $val;
                    }
                }
                $offer['attributes'] = $attrs;
                
                $daoCategory = new Application_Model_DAO_Category();
                $category = $daoCategory->get($bean->categoryId);
                $parentCategory = $daoCategory->get($category['parent_id']);
                $offer['parent_category_code'] = $parentCategory['code'];
                $offer['parent_category_name'] = $parentCategory['name'];
                $offer['category_code'] = $category['code'];
                $offer['category_name'] = $category['name'];
                
                $this->view->offer = $offer;
                $this->renderScript('offer/add-step-preview.phtml');
            }
        }

        if ($currStep == Application_Model_DAO_Offer::STEP_PUBLISH ||
                $currStep == Application_Model_DAO_Offer::STEP_PAYMENT) {
            $formData = $bean->offer;
            $data = array(
                'type' => $bean->type,
                'category_id' => $bean->categoryId,
                'offer_template_id' => $bean->offerTemplateId,
                'author_id' => $this->userId,
                'created_by' => $this->userId,
            );
            $daoOffer = new Application_Model_DAO_Offer();
            $offer = $daoOffer->addNew($formData, $data);
            if (!empty($bean->photos)) {
                $mainPhotoRealId = 0;
                $daoImage = new Application_Model_DAO_Image();
                $imagedata = array(
                    'user_id' => $this->userId,
                    'source_name' => 'offer',
                    'source_id' => $offer['offer_id'],
                );
                $imagesOK = array();
                foreach ($bean->photos as $photo) {
                    $imagedata['filename'] = $photo['name'];
                    $image = $daoImage->addNew($photo['path'], $imagedata);
                    if (empty($image)) {
                        $this->addError($this->_('XXX_OFFER_ADD_PHOTO_ERROR'), array('filename' => $photo['name']));
                        continue;
                    }
                    $imagesOK[] = $image;
                    if ($photo['id'] == $bean->mainPhotoId) {
                        $mainPhotoRealId = $image['image_id'];
                    }
                }
                if ($mainPhotoRealId == 0) {
                    foreach ($imagesOK as $image) {
                        $mainPhotoRealId = $image['image_id'];
                        break;
                    }
                }
                $daoOffer->update($offer['offer_id'], array('image_id' => $mainPhotoRealId));
            }
            Zend_Session::namespaceUnset($bean->getNamespace());
            $bean->unsetAll();
        }

        if ($currStep == Application_Model_DAO_Offer::STEP_PAYMENT) {
            $prop = My_Utils::getOfferProperties();
            $prop = $prop[Application_Model_DAO_Offer::TYPE_PAID];
            $amount = $prop[My_Utils::PROP_OFFER_PRICE];
            $payment = array(
                'source_name' => 'offer',
                'source_id' => $offer['offer_id'],
                'amount' => $amount,
            );
            $daoPayment = new Application_Model_DAO_Payment();
            $payment = $daoPayment->addNew($payment);
            $paymentCode = $payment['code'];
            $url = $this->url(array('controller' => 'payment', 'action' => 'pay', 'id' => $paymentCode));
            $this->_redirect($url);
        }

        if ($currStep == Application_Model_DAO_Offer::STEP_PUBLISH) {
            $url = $this->url(array('controller' => 'offer', 'action' => 'show', 'id' => $offer['code'], 'title' => $offer['title']), 'default', true);
            $this->_redirect($url);
        }
    }

    public function stepPrevAction() {
        $token = $this->_getParam('token');
        $bean = $this->getWizardBean($token);
        $currStep = $bean->currentStep;
        $url = $this->url(array('controller' => 'offer', 'action' => 'add', 'module' => 'default', 'token' => $token));
        switch ($currStep) {
            case Application_Model_DAO_Offer::STEP_CATEGORY:
                $bean->currentStep = Application_Model_DAO_Offer::STEP_LOGIN;
                break;
            case Application_Model_DAO_Offer::STEP_TYPE:
                $bean->currentStep = Application_Model_DAO_Offer::STEP_CATEGORY;
                break;
            case Application_Model_DAO_Offer::STEP_FORM:
                $bean->currentStep = Application_Model_DAO_Offer::STEP_TYPE;
                break;
            case Application_Model_DAO_Offer::STEP_PHOTO:
                $bean->currentStep = Application_Model_DAO_Offer::STEP_FORM;
                break;
            case Application_Model_DAO_Offer::STEP_PREVIEW:
                $bean->currentStep = Application_Model_DAO_Offer::STEP_PHOTO;
                break;
            case Application_Model_DAO_Offer::STEP_PAYMENT:
                $bean->currentStep = Application_Model_DAO_Offer::STEP_PREVIEW;
                break;
        }
        $this->_redirect($url);
    }

    private function getCurrentStep($token = null) {
        if ($token == null) {
            return Application_Model_DAO_Offer::STEP_LOGIN;
        }
        $bean = $this->getWizardBean($token);
        return $bean->currentStep;
    }

    private function initWizard() {
        $token = uniqid();
        $bean = $this->getWizardBean($token);
        $bean->token = $token;
        $bean->currentStep = Application_Model_DAO_Offer::STEP_CATEGORY;
        return $token;
    }

    /**
     * 
     * @param string $token
     * @return Zend_Session_Namespace
     */
    private function getWizardBean($token) {
        return new Zend_Session_Namespace(self::SESSION_KEY . '-' . $token);
    }

    public function indexAction() {
        $id = $this->_getParam('id');
        if (empty($id)) {
            $this->_forward('index', 'category');
            return;
        }
        $daoCategory = new Application_Model_DAO_Category();
        $category = $daoCategory->getByCode($id);
        if (empty($category)) {
            $this->_forward('index', 'category');
            return;
        }
        $category['category_name'] = $category['name'];
        $category['category_code'] = $category['code'];
        if($category['level'] == 2) {
            $this->view->searchForm = new Application_Form_Offer_SearchGeneric($category['offer_template_id']);
            $parentCategoryId = $category['parent_id'];
            $parentCategory = $daoCategory->get($parentCategoryId);
            $category['parent_category_name'] = $parentCategory['name'];
            $category['parent_category_code'] = $parentCategory['code'];
        }
        
        $this->setContentTitle($category['name'], false);
        $this->view->headTitle($category['name']);
        $this->view->category = $category;

        $daoOffer = new Application_Model_DAO_Offer();
        $offers = $daoOffer->getByCategoryId($category['category_id']);
        $this->view->offers = $this->createPaginator($offers);
    }

    public function showAction() {
        $id = $this->_getParam('id');
        if (empty($id)) {
            $this->addError($this->_('XXX_OFFER_SHOW_PAGE_OFFER_DOES_NOT_EXIST'));
            $url = $this->url(array('controller' => 'offer', 'action' => 'index'));
            $this->_redirect($url);
            return;
        }

        $daoOffer = new Application_Model_DAO_Offer();
        $offer = $daoOffer->getOfferByCode($id);
        if (empty($offer)) {
            $this->addError($this->_('XXX_OFFER_SHOW_PAGE_OFFER_DOES_NOT_EXIST'));
            $url = $this->url(array('controller' => 'offer', 'action' => 'index'));
            $this->_redirect($url);
            return;
        }

        $this->setContentTitle($this->view->escape($offer['title']), false);
        $this->view->headTitle($this->view->escape($offer['title']));

        $this->view->offer = $offer;
        $similars = $daoOffer->getOfferSimilars($offer, 5);
        if (!empty($similars)) {
            $this->view->similars = $similars;
        }
    }

}

